package com.chukun.im.server.application.netty.processor.impl;

import com.chukun.im.server.application.netty.cache.UserChannelContextCache;
import com.chukun.im.server.application.netty.processor.MessageProcessor;
import com.chukun.im.server.common.domain.constants.IMConstants;
import com.chukun.im.server.common.domain.enums.IMCmdType;
import com.chukun.im.server.common.domain.enums.IMSendCode;
import com.chukun.im.server.common.domain.model.IMReceiveInfo;
import com.chukun.im.server.common.domain.model.IMSendInfo;
import com.chukun.im.server.common.domain.model.IMSendResult;
import com.chukun.im.server.common.domain.model.IMUserInfo;
import com.chukun.im.server.common.mq.sender.MessageSenderService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chukun
 * @version 1.0.0
 * @description 群聊消息处理器
 * @createTime 2024/5/5 16:43
 */
@Component
public class GroupMessageProcessor implements MessageProcessor<IMReceiveInfo> {

    private final Logger logger = LoggerFactory.getLogger(GroupMessageProcessor.class);

    @Resource
    private MessageSenderService messageSenderService;

    @Async
    @Override
    public void process(IMReceiveInfo receiveInfo) {
        IMUserInfo sender = receiveInfo.getSender();
        List<IMUserInfo> receivers = receiveInfo.getReceivers();
        logger.info("groupMessageProcessor.process,sender:{}，receiver.count:{}，content:{}", sender.getUserId(), receivers.size(), receiveInfo.getData());
        receivers.forEach((receiver) -> {
            try{
                ChannelHandlerContext channelHandlerCtx = UserChannelContextCache.getChannelContext(receiver.getUserId(), receiver.getTerminal());
                if (channelHandlerCtx != null){
                    //向用户推送消息
                    IMSendInfo<?> imSendInfo = new IMSendInfo<>(IMCmdType.GROUP_MESSAGE.code(), receiveInfo.getData());
                    channelHandlerCtx.writeAndFlush(imSendInfo);
                    //发送确认消息
                    sendResult(receiveInfo, receiver, IMSendCode.SUCCESS);
                }else{
                    //未找到用户的连接信息
                    sendResult(receiveInfo, receiver, IMSendCode.NOT_FIND_CHANNEL);
                    logger.error("groupMessageProcessor.process.channel.not.found,sender:{}, receiver:{}, content:{}", sender.getUserId(), receiver.getUserId(), receiveInfo.getData());
                }
            }catch (Exception e){
                sendResult(receiveInfo, receiver, IMSendCode.UNKONW_ERROR);
                logger.error("groupMessageProcessor.process.error,sender:{}, receiver:{}, content:{}, error.message:{}", sender.getUserId(), receiver.getUserId(), receiveInfo.getData(), e.getMessage());
            }
        });
    }

    /**
     * 发送结果数据
     */
    private void sendResult(IMReceiveInfo imReceivenfo, IMUserInfo imUserInfo, IMSendCode imSendCode){
        if (imReceivenfo.getSendResult()){
            IMSendResult<?> imSendResult = new IMSendResult<>(imReceivenfo.getSender(), imUserInfo, imSendCode.code(), imReceivenfo.getData());
            imSendResult.setDestination(IMConstants.IM_RESULT_GROUP_QUEUE);
            messageSenderService.send(imSendResult);
        }
    }

}
